package com.zby.zbyliving.commodity.exception;


import com.zby.common.exception.zbylivingCodeEnum;
import com.zby.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.zby.zbyliving.commodity.controller")
public class zbylivingExceptionControllerAdvice {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(zbylivingCodeEnum.INVALID_EXCEPTION.getCode(),
                zbylivingCodeEnum.INVALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler({Throwable.class})
    public R handleException(Throwable throwable) {
        return R.error(zbylivingCodeEnum.UNKNOWN_EXCEPTION.getCode(),
                zbylivingCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
